<template>
  <div>
<!-- 搜索页面 -->
<form action="/">
  <van-search
    v-model="value"
    show-action
     background="#3296fa"
    placeholder="请输入搜索关键词"
    @search="onSearch"
    @cancel="$router.back()"
    @focus="isShowRes=false"
  />
</form>

<search-results v-if="isShowRes" :searchText="value"/>
<!-- 渲染：把history父向子传值传给子 -->
<search-history @onSearch="onSearch" :history="history" v-else-if="!value" />
<!-- 给联想搜索建议有值时写活 在子组件传props传值 -->
<search-suggestion  @onSearch="onSearch" :searchText="value" v-else />

  </div>
</template>

<script>
import SearchHistory from '@/views/Search/components/SearchHistory'
import SearchResults from '@/views/Search/components/SearchResults'
import SearchSuggestion from '@/views/Search/components/SearchSuggestion'
import { setStorage, getStorage } from '@/utils/storage.js'
export default {
  name: 'Search',
  data () {
    return {
      value: '', // 把搜索的结果展现出来
      isShowRes: false,
      history: getStorage('TT-HISTORY') || []// 存储搜索历史 刷新就本地存储步骤1
    }
  },

  created () {

  },
  watch: {
    history: {
      deep: true,
      handler (val) {
        setStorage('TT-HISTORY', val)
      }
    }
  },
  components: {
    SearchHistory,
    SearchResults,
    SearchSuggestion
  },
  methods: {
    // onSearch () {
    //   console.log('搜索成功')
    //   // this.isShowRes = true
    // },
    // onCancel () {
    //   console.log('取消成功')
    // },
    onSearch (val) { // 掉的注册事件后面的方法
      this.value = val
      this.isShowRes = true
      // 进行搜索历史的存储
      this.history.unshift(val)
      this.history = [...new Set(this.history)]// Set:数组去重 把搜索历史相同的去重
    }
  }
}
</script>

<style scoped lang='less'>
.van-search__action{
color: #fff;
}
</style>
